package cn.qlin.mvc.orm;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.qlin.mvc.orm.bean.Where;
import cn.qlin.mvc.orm.util.BeanOperate;
import cn.qlin.mvc.orm.util.CreateSql;
import cn.qlin.mvc.orm.util.ORMAnnotationOpen;
import cn.qlin.util.Reflect;

public class QlinDB {
	public static Connection conn = null;
	static {
		String user = "root";
		String pwd = "12345";
		String driver = "org.gjt.mm.mysql.Driver";
		String url = "jdbc:mysql://127.0.0.1:3306/spider?characterEncoding=utf8";
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, pwd);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("数据库链接异常请检测驱动，数据库信息等。。。");
			;
		}
	}
	/**
	 * @author吴延麟
	 * 描述：对象的新增
	 * */
	public int add(Object obj){
		Class<?> clz = obj.getClass();
		String sql = null;
		PreparedStatement ps;
		try {
			sql = new CreateSql().createInsert(BeanOperate.getInsert(obj),ORMAnnotationOpen.getClassToTb(clz));
			ps = conn.prepareStatement(sql);
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	/**
	 * @author吴延麟
	 * 描述：对象的删除
	 * */
	public int delete(Object obj) {
		Class<?> clz = obj.getClass();
		String sql = null;
		try {
			sql = new CreateSql().createDelete(BeanOperate.getdelete(obj), ORMAnnotationOpen.getClassToTb(clz));
			PreparedStatement ps = conn.prepareStatement(sql);
			return ps.executeUpdate();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	/**
	 * @author吴延麟
	 * 描述：对象的修改
	 * */
	public int update(Object obj) {
		Class<?> clz = obj.getClass();
		String sql = null;
		try {
			sql = new CreateSql().createUpdate(BeanOperate.getupdate(obj), ORMAnnotationOpen.getClassToTb(clz));
			PreparedStatement ps = conn.prepareStatement(sql);
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
	/**
	 * @author吴延麟
	 * 描述：对象的查询（所有查询）
	 * */
	public List<Object> query(Class<?> clz) {
		return query(clz,new Where());
	}
	/**
	 * @author吴延麟
	 * 描述：对象的查询（带条件查询）
	 * */
	public List<Object> query(Class<?> clz,Where where) {
		List<Object> obj = new ArrayList<Object>();
		Map<String,Field> col = BeanOperate.getALLColsName(clz);
		List<String> cols = new ArrayList<String>();
		List<Field> fields = new ArrayList<Field>();
		Set<String> it = col.keySet();
		for(String s:it){
			cols.add(s);
			fields.add(col.get(s));
		}
		try {
			String sql = CreateSql.creatQuery(cols, ORMAnnotationOpen.getClassToTb(clz), where);
			System.out.println(sql);
			PreparedStatement ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				Reflect ref = new Reflect(clz);
				for (int i=0; i<fields.size();i++) {
					Field field = fields.get(i);
					String coltype = Reflect.getFieldType(field);
					if("string".equals(coltype)){
						String fieldName = BeanOperate.getFieldName(field);
						if(!("".equals(fieldName))){
							ref.set(field, rs.getString(fieldName));
						}
					}else if("int".equals(coltype)){
						String fieldName = BeanOperate.getFieldName(field);
						if(!("".equals(fieldName))){
							ref.set(field, rs.getInt(fieldName));
						}
					}
				}
				obj.add(ref.getObj());
			}
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return obj;
	}
	/**
	 * @author吴延麟
	 * 描述：对象的查询（根据id查询）
	 * */
	public Object queryById(Class<?> clz,Object id) {
		Where where = new Where();
		if(id.getClass().getName().toString()=="java.lang.String"){
			where.add(BeanOperate.getIdToName(clz)+"='"+id+"'");
		}else if(id.getClass().getName().toString()=="java.lang.Integer"){
			where.add(BeanOperate.getIdToName(clz)+"="+id+"");
		}
		System.out.println(where);
		List<Object> obj = query(clz,where);
		if(obj.size()<1){
			return null;
		}else{
			return obj.get(0);
		}
	}
	
	
	
}
